/*
 * CodeDict.cpp
 *
 *  Created on: 2022-01-08
 *      Author: chuanjiang.zh
 */

#include "CodeDict.h"
#include "IniFile.h"
#include "TStringUtil.h"

//#include "CLog.h"

CodeDict::CodeDict()
{
}

CodeDict::~CodeDict()
{
    clear();
}

bool CodeDict::load(const std::string& filepath, const std::string& section, Map& wordMap)
{
    comn::IniFile iniFile;
    if (!iniFile.load(filepath.c_str()))
    {
        return false;
    }

    if (iniFile.getSectionCount() <= 0)
    {
        return false;
    }

    comn::IniFile::IniSection* iniSection = nullptr;
    if (iniFile.existSection(section.c_str()))
    {
        iniSection = &(iniFile.ensure(section.c_str()));
    }
	else
	{
        return false;
	}

    for (size_t i = 0; i < iniSection->size(); ++i)
    {
        std::string key;
        std::string value;
        iniSection->at(i, key, value);

		//CLog::info("CodeDict. key: %s, value: %s\n", key.c_str(), value.c_str());

        int num = 0;
        comn::StringCast::toValue(key, num);

        wordMap[num] = value;
    }

    return true;
}

bool CodeDict::load(const std::string& filepath, const std::string& sectionName)
{
	bool got = false;
	Map wordMap;
	if (load(filepath, sectionName, wordMap))
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		m_map = wordMap;
		got = true;
	}

    return got;
}

bool CodeDict::find(int key, std::string& value)
{
    bool got = false;
    std::lock_guard<std::mutex> lock(m_mutex);

    Map::iterator it = m_map.find(key);
    if (it != m_map.end())
    {
        value = it->second;
        got = true;
    }
    return got;
}

std::string CodeDict::get(int key, const char* defValue)
{
    std::lock_guard<std::mutex> lock(m_mutex);

    Map::iterator it = m_map.find(key);
    if (it != m_map.end())
    {
        return it->second;
    }
    return std::string(defValue);
}

void CodeDict::clear()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    m_map.clear();
}

size_t CodeDict::size()
{
    std::lock_guard<std::mutex> lock(m_mutex);
    return m_map.size();
}

bool CodeDict::exists(int key)
{
    std::lock_guard<std::mutex> lock(m_mutex);

    Map::iterator it = m_map.find(key);
    return it != m_map.end();
}

void CodeDict::put(int key, const std::string& value)
{
    std::lock_guard<std::mutex> lock(m_mutex);
    m_map[key] = value;
}
